const jwt = require("jsonwebtoken");
const { JWT_SCRIPT } = require("../config/config.default");
const { createUser, getUserInfo } = require("../service/user.service");
const { userRegisterError } = require("../constant/err.type");
class UserController {
  async register(ctx, next) {
    //1.获取前端发过来的数据
    // console.log(ctx.request.body);
    const { user_name, password } = ctx.request.body;
    //2.操作数据库  抽离出来 单独操作   service层
    try {
      const res = await createUser(user_name, password);
      //3.返回结果
      ctx.body = {
        code: 0,
        message: "用户注册成功",
        result: {
          id: res.id,
          user_name: res.user_name,
        },
      };
    } catch (err) {
      console.log(err);
      ctx.app.emit("error", userRegisterError, ctx);
    }
  }
  async login(ctx, next) {
    const { user_name } = ctx.request.body;
    // ctx.body = `登录成功!欢迎回来,${user_name}`;
    //1.获取用户信息(在token的payload中,记录id,user_name,is_admin)
    try {
      //使用getUserInfo查出来的有id，name，password，isadmin四个字段，我们不需要password 这里是剔除方法从里面去掉了password
      const { password, ...res } = await getUserInfo({ user_name });
      ctx.body = {
        code: 0,
        message: "登录成功!",
        token: jwt.sign(res, JWT_SCRIPT, { expiresIn: "1d" }),
      };
    } catch (err) {
      console.error("用户登录失败", err);
    }
  }
}

module.exports = new UserController();
